package com.tang.config;

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.ScheduledUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import lombok.Getter;
import lombok.Setter;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;

@Configuration
@ConfigurationProperties(prefix = "wxpay")
@Getter
@Setter
public class WXPayConfig {
 private String mchId;
 private String mchSerialNo;
 private String privateKeyPath;
 private String apiV3Key;
 private String appid;
 private String domain;
 private String notifyDomain;

 /**
  * 获取商户私钥
  * @param filename
  * @return
  */
 private PrivateKey getPrivateKey(String filename){
  try {
   return PemUtil.loadPrivateKey(new FileInputStream(filename));
  } catch (FileNotFoundException e) {
   throw new RuntimeException("私钥文件不存在", e);
  }
 }

 /**
  * 获取签名验证器
  * @return
  */
 @Bean
 public ScheduledUpdateCertificatesVerifier getVerifier(){
//获取商户私钥
  PrivateKey privateKey = getPrivateKey(privateKeyPath);
//私钥签名对象（签名）
  PrivateKeySigner privateKeySigner = new PrivateKeySigner(mchSerialNo,
          privateKey);
//身份认证对象（验签）
  WechatPay2Credentials wechatPay2Credentials = new
          WechatPay2Credentials(mchId, privateKeySigner);
// 使用定时更新的签名验证器，不需要传入证书
  ScheduledUpdateCertificatesVerifier verifier = new
          ScheduledUpdateCertificatesVerifier(
          wechatPay2Credentials,
          apiV3Key.getBytes(StandardCharsets.UTF_8));
  return verifier;
 }

 /**
  * 获取HttpClient对象
  * @param verifier
  * @return
  */
 @Bean
 public CloseableHttpClient getWxPayClient(ScheduledUpdateCertificatesVerifier verifier){
 //获取商户私钥
  PrivateKey privateKey = getPrivateKey(privateKeyPath);


//用于构造HttpClient
  WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
          .withMerchant(mchId, mchSerialNo, privateKey)
          .withValidator(new WechatPay2Validator(verifier));
  WechatPayHttpClientBuilder builder1 = WechatPayHttpClientBuilder.create()
          .withMerchant(mchId, mchSerialNo, privateKey)
          .withValidator(new WechatPay2Validator(verifier));
// ... 接下来，你仍然可以通过builder设置各种参数，来配置你的HttpClient
// 通过WechatPayHttpClientBuilder构造的HttpClient，会自动的处理签名和验签，并进行证书自动更新
  CloseableHttpClient httpClient = builder.build();
  return httpClient;
 }
}